package com.meta.pic.view

import android.util.Log
import com.airbnb.mvrx.BaseMvRxViewModel
import com.airbnb.mvrx.Loading
import com.meta.pic.Result
import com.meta.pic.io.HomeRepository
import com.meta.pic.util.Singletons
import io.reactivex.Observable

class HomeViewModel(state: HomeState) : BaseMvRxViewModel<HomeState>(state, false) {

    private val homeRepository =
        HomeRepository(Singletons.retrofit)
    fun setLocation(location: String) {
        withState {
            setState { it.copy(location = location) }
        }
    }

    /**
     * @param loadMore
     * @param location
     */
    fun loadData(loadMore: Boolean) {
        withState { state ->
            if (state.request is Loading) return@withState
            val page = if (!loadMore) {
                0
            } else {
                state.nextPage
            }

            Observable.create<Result> {
                val response = homeRepository.getPics(state.location, page, 15)
                val body = response.body()
                if (body != null) {
                    it.onNext(body)
                } else {
                    it.onError(IllegalArgumentException(""))
                }
                it.onComplete()
            }.map {
                it.list to if (!loadMore) 1 else if (it.end) 0 else state.nextPage + 1
            }.execute {
                val result = it()
                val newItems = result?.first ?: emptyList()
                val newPage = result?.second ?: -1

                copy(
                    request = it,
                    list = if (!loadMore) newItems else list + newItems,
                    nextPage = newPage
                )
            }
        }
    }

    fun toggleLayoutType() {
        withState {
            val newType =
                if (it.layoutType == HomeState.GRID) HomeState.STAGGERED_GRID else HomeState.GRID
            setState {
                it.copy(layoutType = newType,
                    list = list.mapIndexed { index, picItem ->
                        picItem.copy(
                            ratio = if (newType == HomeState.GRID) {
                                1F
                            } else {
                                when {
                                    index % 2 == 0 -> {
                                        1.2F
                                    }
                                    index % 3 == 0 -> {
                                        0.6F
                                    }
                                    else -> {
                                        0.4F
                                    }
                                }
                            }
                        )
                    })
            }
        }
    }


}


